const data = [
  [1, 2, 3],
  [true, false, null, 'sheetjs'],
  ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
  ['baz', null, 'qux'],
];
var buffer = window.$xlsx.build([{ name: 'mySheetName', data: data }]);
// 生成excel文件
export async function createExcel(buffer, path = '') {
  if (!path) {
    path =
      window.$config.lang[0].file.split('/').slice(0, -1).join('/') +
      '/excel.xlsx';
  }
  console.log('path', path);

  await window.$createFileIfNotExist(path);
  await window.$writeFile(path, buffer);
}
// 获取配置中所有的语言
async function getAllLan() {
  let res = [];
  for (let i = 0; i < window.$config.lang.length; i++) {
    const one = window.$config.lang[i];
    let arr = one.file.split('.');
    let obj = {};
    const fileType = arr[arr.length - 1];
    if (fileType === 'json') {
      const res = window.$readFile(one.file);
      obj = JSON.parse(res);
      console.log('readFile', obj);
    } else if (fileType === 'js') {
      if (!window.$checkFileExists(one.file)) {
        await window.$createFileIfNotExist(one.file);
        await window.$writeFile(one.file, 'export default {}');
        await window.$sleep(0.01);
      }
      obj = (await import(one.file)).default;
      console.log(obj);
    } 
    else if (fileType === 'ts') {
      if (!window.$checkFileExists(one.file)) {
        await window.$createFileIfNotExist(one.file);
        await window.$writeFile(one.file, 'export default {}');
        await window.$sleep(0.01);
      }
      let res = window.$readFile(one.file);
      let tempFile = window.$createTempFile(res);
      console.log("tempFile", tempFile);
      // 转js
      obj = await import(tempFile);
      console.log(obj);
    }
    else {
      alert('仅支持JSON,js,ts文件');
    }
    res.push({
      code: one.code,
      name: one.name,
      file: one.file,
      obj,
      map: getKeyValueFromObj(obj),
    });
    console.log('keys', Object.keys(obj));
  }
  console.log('getAllLan', res);
  return res;
}

// 遍历所有的obj找出所有键值对 生成Map
function getKeyValueFromObj(obj, pKey = '') {
  let map = new Map();
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      let _map = getKeyValueFromObj(obj[key], pKey ? pKey + '.' + key : key);
      //  合并Map
      map = new Map([...map, ..._map]);
    } else {
      map.set(pKey ? pKey + '.' + key : key, obj[key]);
    }
  }
  return map;
}

$('#excel').on('click', async () => {
  const fileArr = utools.showOpenDialog({
    filters: [{ name: '' }],
    properties: ['openDirectory'],
  });
  console.log('file', fileArr);
  const fpath = fileArr[0] + '/excel.xlsx';
  console.log('clickExcel');
  const list = await getAllLan();
  let allMap = new Map();
  //   生成表头 [props,lang1,lang2....]
  const head = ['key'];
  list.forEach((item, index) => {
    head.push(`${item.code}|${item.name}|${item.file}`);
    // 归类
    if (index === 0) {
      const keys = [...item.map.keys()];
      keys.forEach((key) => {
        allMap.set(key, [
          {
            index,
            value: item.map.get(key),
            code: item.code,
          },
        ]);
      });
    } else {
      const keys = [...item.map.keys()];
      keys.forEach((key) => {
        if (allMap.get(key)) {
          allMap.set(key, [
            ...allMap.get(key),
            {
              index,
              value: item.map.get(key),
              code: item.code,
            },
          ]);
        } else {
          // 之前不存在的多语言
          allMap.set(key, [
            {
              index,
              value: item.map.get(key),
              code: item.code,
            },
          ]);
        }
      });
    }
  });
  console.log('allMap', allMap);
  //  获取到所有的语言文件与对应的译文
  console.log('head', head);
  const data = [head];
  //   根据Map keys 作为行a1进行添加
  allMap.forEach((item, key) => {
    const row = [key];
    item.forEach((one) => {
      row[one.index + 1] = one.value;
    });
    data.push(row);
  });
  var buffer = window.$xlsx.build([{ name: 'languageList', data: data }]);
  createExcel(buffer, fpath);
});

$('#importExcel').on('click', () => {
  const fileArr = utools.showOpenDialog({
    filters: [{ name: '', extensions: ['xlsx'] }],
    properties: ['openFile'],
  });
  console.log('file', fileArr);
  const fpath = fileArr[0];
  excelToJSON(fpath);
});

async function excelToJSON(file) {
  const workSheetsFromFile = window.$xlsx.parse(file);
  console.log('workSheetsFromFile', workSheetsFromFile);
  // 反向解析
  // 1. 获取/生成文件路径
  const data = workSheetsFromFile[0].data;
  console.log('data', data);
  let langTypes = data[0]
  langTypes.shift()
  langTypes= langTypes.map((item, index) => {
    console.log('item',item)
    const arr = item.split('|');
    const code = arr[0];
    const file = arr[2];
    if (!file) {
      utools.showNotification(`错误:${code} excel中没有导出文件路径!!!`);
      throw '错误: excel中没有导出文件路径!!!';
    }
    const fileName = arr[2]?.split('/').at(-1);
    return { code, file, index, fileName, obj: {} };
  });
  console.log('langTypes', langTypes);
  // 遍历data 将第一个元素作为key 写入obj
  data.forEach(async (one, index) => {
    let key = '';
    if (index === 0) return;
    one.forEach((word, i) => {
      if (i === 0) {
        key = word;
        return;
      }
      window.$addKey(key, word, langTypes[i - 1].obj, false);
    });
    console.log('langTypes', langTypes);
  });
  //   langTypes.forEach(async (one, index) => {

  //   });
  for (let i = 0; i < langTypes.length; i++) {
    let one = langTypes[i];
    console.log('one',one)
    let arr = one.file.split('.');
    const fileType = arr[arr.length - 1];
    if (fileType === 'json') {
      await window.$writeFile(one.file, JSON.stringify(one.obj, null, 2));
    } else if (fileType === 'js') {
      if (!window.$checkFileExists(one.file)) {
        await window.$createFileIfNotExist(one.file);
        await window.$writeFile(one.file, 'export default {}');
        await sleep(0.1);
      }
      await window.$writeFile(
        one.file,
        'export default ' + JSON.stringify(one.obj, null, 2)
      );
    }
    else if (fileType === 'ts') {
      if (!window.$checkFileExists(one.file)) {
        await window.$createFileIfNotExist(one.file);
        await window.$writeFile(one.file, 'export default {}');
        await sleep(0.1);
      }
      await window.$writeFile(
        one.file,
        'export default ' + JSON.stringify(one.obj, null, 2)
      );
    }
     else {
      alert('仅支持JSON,js,ts文件');
    }
  }
  console.log('importExcel', '导入完成!');
  utools.showNotification('导入完成!');
}
